import { Base64Decoder, matchFileType } from 'src/assets/js/util'
import { getDownloadRecord, readFile as readFileCloud, readFile } from 'src/boot/program-v2/cloud'
import { cncToBox, fileMachineLocal } from 'src/boot/program-v2/machine'
import { getNewBox } from 'src/boot/program-v2/program-transfer'
import boxCodeErr from 'src/assets/json/boxCodeErr'
import boxErr from 'src/assets/json/boxErr'
import { readFile as readFileLocal } from 'src/assets/js/file-dir'
const base64Decoder = new Base64Decoder()
import _ from 'lodash'
export default {
  name: 'file-minxins',
  methods: {
    // 读取设备端文件
    readMachineFile (item, prevContent) {
      if (item.position === 'cnc') {
        this.putMachineInside(item, prevContent)
      } else {
        this.putMachine(item, item.path, prevContent)
      }
    },
    // 开始发送内部存储文件到外部存储文件
    async putMachineInside (send, prevContent) {
      let requestId1 = 'webClient' + this.userInfo.user_id.toString() + Date.parse(new Date()).toString()
      // let self = this
      let params1 = {
        deviceId: send.deviceId,
        cncPath: send.path,
        boxPath: '',
        requestId: requestId1
      }
      let onMessageArrived = (res) => {
        let data = JSON.parse(res.body).data
        console.log(data)
        try {
          // 这里是放置对其他消息进行处理
          if (requestId1 === data.request_id && data.hasOwnProperty('error')) {
            if (data.error === 0) {
              this.putMachine(send, data.file_path, prevContent)
            } else {
              this.$q.loading.hide()
              this.errMessage(`文件${send.label}读取失败！${boxErr[data.error]} 请刷新重试`)
            }
          }
        } catch (e) {
          console.error(e)
          this.errMessage('文件内容读取超时! 请刷新重试')
        }
      }
      let newBoxList = await getNewBox([send.deviceId])
      if (!_.isEmpty(newBoxList.data)) {
        const boxRemark = newBoxList.data[0].boxRemark
        if (boxRemark === 1) {
          // 直接走下载
          this.putMachine(send, send.path, prevContent)
        } else {
          let ret = await cncToBox(params1)
          if (!ret.success) return
          if (ret.success) {
            if (ret.data.source === 0) {
              this.onSubscribe(send.deviceId, onMessageArrived)
            }
          }
        }
      }
    },
    // 获取随机数 默认1-2147483647
    getRandom (min = 1, max = 2147483647) {
      min = Math.ceil(min)
      max = Math.floor(max)
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    // 从机床传输到云端的方法
    putMachine (send, path, prevContent) {
      // let self = this
      let isNewUlrState = false
      let urlNew = null
      const requestIdNew = this.getRandom()
      let params = {
        deviceId: send.deviceId,
        fileName: send.label,
        requestId: requestIdNew,
        filePath: path,
        fromBox: send.position === 'box' ? 1 : 0
      }
      let onMessageArrived = (res) => {
        let data = JSON.parse(res.body).data
        console.log(data)
        try {
          // 这里是放置对其他消息进行处理
          if (requestIdNew === Number(data.request_id)) {
            if (data.hasOwnProperty('source') && data.source === 'send_result') {
              if (data.code === 200) {
                // 盒子上传到云端已完成，接下来是从云端获取内容
                this.getFileContentNew(send, data.url, prevContent)
              } else {
                this.$q.loading.hide()
                this.errMessage(`文件${send.label}读取失败！${boxCodeErr[data.code]}`)
              }
            }
          }
        } catch (e) {
          console.error(e)
          this.errMessage('文件内容读取失败')
        }
        this.onUnSubscribeResultBox(requestIdNew)
      }
      this.onSubscribe2(requestIdNew, onMessageArrived)
      this.onSubscribeNewBox(requestIdNew, (mes) => {
        this.loading = false
        let data = JSON.parse(mes.body).data
        console.log(data)
        if (data.cmd_ID === requestIdNew) {
          if (data.errorCode === '2000' || data.errorCode === '3000') {
            isNewUlrState = true
            if (!_.isNil(urlNew)) {
              this.getFileContentNew(send, urlNew, prevContent)
            } else {
              return
            }
          } else {
            this.errMessage(`文件${send.label}读取失败！${boxCodeErr[data.errorCode]}`)
          }
          this.onUnSubscribeNewBox(requestIdNew)
        }
      })
      fileMachineLocal(params).then(res => {
        urlNew = res.data.url
        // requestId = res.data.requestId
        if (res.data.source === '1') {
          if (requestIdNew === Number(res.data.requestId)) {
            if (isNewUlrState) {
              this.getFileContentNew(send, res.data.url, prevContent)
              this.onUnSubscribeNewBox(requestIdNew)
            }
          }
        }
      })
    },
    // 新的下载文件
    getFileContentNew (send, url, prevContent) {
      const params = {
        cloudPath: url
      }
      getDownloadRecord(params).then(res => {
        const dataString = base64Decoder.decode(res.data)
        let machineContent = {
          title: send.label,
          content: dataString
        }
        if (prevContent) {
          this.$refs.codeMerge.showDialog(prevContent, machineContent)
          this.$refs.CompareFile.hide()
          this.$q.loading.hide()
        } else {
          let machineItem = this.compareList[1]
          this.readMachineFile(machineItem, machineContent)
        }
      }).catch(() => {
        this.$q.loading.hide()
      })
    },
    // 下面是文件对比相关
    // 加入对比列表
    addCompareList (file) {
      if (!this.allowSize(file)) return
      this.$refs.CompareFile.show(file)
      this.actFile = []
    },
    // 读取文件内容，弹出比较弹框
    compareDetail (compareList) {
      let machineArr = compareList.filter(item => item.source === 'machine')
      let machineFileNum = machineArr.length
      console.log(machineArr)
      this.compareList = compareList
      this.$q.loading.show()
      // 没有机床文件
      if (machineFileNum === 0) {
        const result = this.readFile(compareList)
        Promise.all(result).then(res => {
          let content1 = {
            title: compareList[0].label,
            content: res[0].data
          }
          let content2 = {
            title: compareList[1].label,
            content: res[1].data
          }
          this.$refs.codeMerge.showDialog(content1, content2)
          this.$refs.CompareFile.hide()
        }).finally(() => {
          this.$q.loading.hide()
        })
      } else if (machineFileNum === 1) {
        // 先读取云端或本地文件
        const result = this.readFile(compareList)
        Promise.all(result).then(res => {
          let content1 = {
            title: compareList.find(v => v.source !== 'machine').label,
            content: res[0].data
          }
          // 再读取机床文件
          this.readMachineFile(machineArr[0], content1)
        })
      } else if (machineFileNum === 2) {
        // 两个都为机床文件的对比
        let machineItem = compareList[0]
        this.readMachineFile(machineItem)
      }
      setTimeout(() => {
        this.$q.loading.hide()
      }, 8000)
    },
    // 读取本地和云端对比文件的内容
    readFile (compareList) {
      let result = []
      compareList.forEach(item => {
        // 读取云端内容
        if (item.source === 'cloud') {
          result.push(readFileCloud(item.path))
        }
        // 读取本地文件内容
        if (item.source === 'local') {
          let getFileLocal = new Promise((resolve, reject) => {
            readFileLocal(item.file,
              () => {
                this.errMessage('文件读取失败')
                reject('文件读取失败')
              },
              (str, decode) => {
                resolve({ data: str })
              })
          })
          result.push(getFileLocal)
        }
      })
      return result
    },
    // 编辑读取文件
    editFile (item) {
      if (matchFileType(item.label)) {
        this.errMessage('无法编辑图片文件、word文件、视频文件、音频文件、快捷方式、压缩文件！')
        return
      }
      if (!this.testFileSize(item)) return
      this.editFileName = item.label
      readFile(item.path).then(res => {
        this.editFileContent = res.data
        this.editFilePath = item.path
        this.codeState = 'edit'
        this.editCurFile = item
        this.$refs.codeEdit.showDialog()
      })
    },
    // 文件校验
    // 比较文件的大小是否符合规则
    allowSize (compareList) {
      if (matchFileType(compareList.label)) {
        this.errMessage('无法对比图片文件、word文件、视频文件、音频文件、快捷方式、压缩文件！')
        return false
      }
      if (compareList.source === 'local' && compareList.size > 5 * 1024 * 1024) {
        this.errMessage('无法对比超过5M的本地文件')
        return false
      }
      if (compareList.source === 'cloud' && compareList.size > 5 * 1024 * 1024) {
        this.errMessage('无法对比超过5M的云端文件')
        return false
      }
      if (compareList.source === 'machine' && compareList.size > 1024 * 1024) {
        this.errMessage('无法对比超过1M的机床文件')
        return false
      }
      return true
    },
    // 验证文件大小是否超过5M
    testFileSize (file) {
      if (file.size > 5 * 1024 * 1024) {
        this.errMessage('文件超过5M暂不支持查看！')
        return false
      }
      return true
    },
    // 显示版本履历
    showVersionList (file) {
      this.$refs.versionList.showDialog(file)
    },
    // 存储拖动数据
    setDragItem (item) {
      this.actFile = [item]
      this.dragItem = [item]
    },
    // 提示
    // 注意提示
    noticeMessage (message) {
      this.$message.warning(message)
    },
    // 成功提示
    successMessage (message) {
      this.$message.success(message)
    },
    // 失败提示
    errMessage (message) {
      this.$message.error(message)
    }
  }
}
